package xjh.him.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xjh.him.R;

import java.net.InetSocketAddress;

import xjh.him.common.BgTaskActivity;
import xjh.him.common.ErrorMsg;
import xjh.him.common.SharedData;
import xjh.him.netty.NettyClient;
import xjh.him.netty.codec.Command;
import xjh.him.netty.codec.Packet;
import xjh.him.netty.dto.UserDto;
import xjh.him.util.LogcatUtil;
import xjh.him.util.ToastUtil;


public class LoginActivity extends BgTaskActivity {
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        registerUrlOnClick();
        login();
    }

    public void registerUrlOnClick() {
        TextView registerUrl = findViewById(R.id.register_url);
        registerUrl.setOnClickListener((view) -> {
            Intent regIntent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(regIntent);
            finish();
        });
    }

    public void login() {
        Button loginBtn = findViewById(R.id.login);
        loginBtn.setOnClickListener((view -> {
            EditText phoneText = findViewById(R.id.login_phone);
            EditText pwdText = findViewById(R.id.login_pwd);

            NettyClient client = SharedData.client;
            if (client == null) {
                client = new NettyClient();
                SharedData.client = client;
                InetSocketAddress address = new InetSocketAddress(
                        getString(R.string.netty_server_address),
                        Integer.parseInt(getString(R.string.netty_server_port)));
                client.connect(address);
            }

            UserDto.LoginReq req = new UserDto.LoginReq();
            req.setPhone(phoneText.getText().toString());
            req.setPassword(pwdText.getText().toString());
            client.sendMsg(new Packet(
                    Command.getCommand(UserDto.LoginReq.class),
                    JSON.toJSONString(req)
            ));
            Object obj = SharedData.future.get();
            if (obj instanceof UserDto.LoginResp) {
                UserDto.LoginResp resp = (UserDto.LoginResp) obj;
                SharedData.me = resp.getUser();
                SharedData.token = resp.getToken();
            }else if (obj instanceof ErrorMsg) {
                ToastUtil.show(this, ((ErrorMsg)obj).getMsg());
                return;
            }

            LogcatUtil.i("fetch data success");

            Intent homeIntent = new Intent(LoginActivity.this, HomeActivity.class);
            startActivity(homeIntent);
            finish();
        }));
    }
}